package com.unohacha.qqj.fzdr.main.sends;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.superhttp.request.UploadRequest;
import com.qpg.widget.common.ToastUtil;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.LabelCategaryAdapter;
import com.unohacha.qqj.fzdr.adapter.imgpicker.FabricImagePickerAdapter;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.BooleanModel;
import com.unohacha.qqj.fzdr.bean.CatData;
import com.unohacha.qqj.fzdr.bean.ImgBean;
import com.unohacha.qqj.fzdr.bean.LabelBean;
import com.unohacha.qqj.fzdr.bean.LevelThreeClassBean;
import com.unohacha.qqj.fzdr.bean.PickerDataBean;
import com.unohacha.qqj.fzdr.bean.PostingModle;
import com.unohacha.qqj.fzdr.bean.PublishTip;
import com.unohacha.qqj.fzdr.bean.citybean.DistrictModel;
import com.unohacha.qqj.fzdr.bean.citybean.ProvinceBean;
import com.unohacha.qqj.fzdr.bean.citybean.ProvinceModel;
import com.unohacha.qqj.fzdr.bean.citybean.TownModle;
import com.unohacha.qqj.fzdr.ui.activity.PubSettlementActivity;
import com.unohacha.qqj.fzdr.util.FastUtils;
import com.unohacha.qqj.fzdr.util.GetJsonDataUtil;
import com.unohacha.qqj.fzdr.util.GlideImageLoaderForPicker;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.TimeUtils;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.fzdr.view.FullyGridLayoutManager;
import com.unohacha.qqj.fzdr.view.MyGridView;
import com.unohacha.qqj.fzdr.view.PublicStaticData;
import com.unohacha.qqj.fzdr.view.citypickview.CityPickerPopWindow2;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.youth.picker.PickerView;
import com.youth.picker.entity.PickerData;
import com.youth.picker.listener.OnPickerClickListener;

import org.json.JSONArray;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParserFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 物流发布
 */
public class SendWlActivity extends BaseActivity implements FabricImagePickerAdapter.OnRecyclerViewItemClickListener, CityPickerPopWindow2.CityPickListener {
    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.ll_classify)
    LinearLayout llClassify;
    @BindView(R.id.ll_label)
    LinearLayout llLabel;
    @BindView(R.id.et_company_name)
    EditText etFormat;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_label_count)
    TextView tvLabelCount;
    @BindView(R.id.gv_sing_style)
    MyGridView gridView;
    @BindView(R.id.et_contact)
    EditText etTxtra;
    LabelCategaryAdapter labelCategaryAdapter;
    @BindView(R.id.show_area_tv)
    TextView show_area_tv;
    @BindView(R.id.show_area_rl)
    RelativeLayout showAreaRl;
    @BindView(R.id.root_layout)
    LinearLayout root_layout;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.detail_et)
    EditText detailEt;
    @BindView(R.id.et_start)
    TextView etStart;
    @BindView(R.id.et_middle)
    TextView etMiddle;
    @BindView(R.id.et_end)
    TextView etEnd;
    @BindView(R.id.rl_start)
    RelativeLayout rlStart;
    @BindView(R.id.rl_end)
    RelativeLayout rlEnd;

    private OptionsPickerView pvOptionsType;
    private String fabricName, fabricId;
    ArrayList<CatData.Two> listsDetial;
    ArrayList<PublishTip> listsCateName;
    ArrayList<LabelBean> listLabel;
    List<CatData> listTwo;
    HashMap<String, String> map;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private FabricImagePickerAdapter imagePickerAdapter;
    public static ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 1;               //允许选择图片最大数
    private String mainId = "";

    private String[] mTitles;//标题的提示的数组
    private String[] mSpecs;//规格的提示数组
    private String[] mContents;//其他内容提示数组
    private String[] mNumberss;//产品数量的数组
    private String[] mNumUnits;//数量单位的数组
    private String[] mOnePrices;//单价提示的数组
    private String[] mOnePriceUnits;//单价单位的数组
    private int type = 1;//1供应 2 需求

    private OptionsPickerView pvFirstLevel, pvSecondLevel, pvThirdLevel;
    private ArrayList<String> firstLevle, secondLevel, thirdLevel;
    BaseBean<List<LevelThreeClassBean>> oneLevelList;
    List<LevelThreeClassBean.TwoBean> twoLevelList;
    private List<ProvinceBean> options1Items = new ArrayList<>();
    private List<ProvinceBean.TwoRegBean> options2Items = new ArrayList<>();
    private List<ProvinceBean.TwoRegBean.ThreeRegBean> options3Items = new ArrayList<>();
    private String provinceId = "1";// 省id
    private String cityId = "2";//市 id
    private String distristId = "3";//区id
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private Thread thread;
    private boolean isLoaded = false;
    private String province, city, district;
    private int startOnEnd;

    /**
     * 所有省
     */
    private String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    private Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    private Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 镇
     */
    private Map<String, String[]> mTownDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    private Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    private String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    private String mCurrentCityName;
    /**
     * 当前区的名称
     */
    private String mCurrentDistrictName ="";

    /**
     * 当前区的邮政编码
     */
    private String mCurrentZipCode ="";
    
    private List<PickerDataBean.CityBean> cityList;
    private List<PickerDataBean.CityBean.ReaBean> reaList;
    private List<PickerDataBean.CityBean.ReaBean.TownBean> townList;
    private List<PickerDataBean> provinceList;
    
    private PickerView pickerView;
    private PickerData pickerData;
    
    private int journeyCityId,journeyAreaId,journeyTownId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_wl;
    }

    @Override
    protected void initView() {
        commonRightImage.setVisibility(View.INVISIBLE);
        commonTitle.setText("物流发布");
        String str = "sdfs#d";
        Log.d("sssssss",str.substring(0, str.indexOf("#"))+"   "+str.substring(str.indexOf("#")));
        map = new HashMap<>();
        mainId = getIntent().getStringExtra("main_id");
        type = getIntent().getIntExtra("type", 0);
        fabricName = getIntent().getStringExtra("name");
        fabricId = getIntent().getStringExtra("id");
        tvType.setText(fabricName);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        listTwo = new ArrayList<>();
        initImagePicker();
        selImageList = new ArrayList<>();
        imagePickerAdapter = new FabricImagePickerAdapter(this, selImageList, maxImgCount);
        imagePickerAdapter.setOnItemClickListener(this);

        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(imagePickerAdapter);
        pvOptionsType = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvType.setText(listsDetial.get(options1).getName());
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                labelCategaryAdapter.chiceState(position);
                tvLabelCount.setText(labelCategaryAdapter.getSelectCount() + "个");
            }
        });

//        PickerDataBean pickerDataBean = new PickerDataBean();
        initProvinceDatas();

        pickerData = new PickerData();

        getLabelData();
        getTips();

    }

    private void initProvinceDatas() {

        /**
         * 解析省市区的XML数据
         */
        SuperHttp.post("api/region/openProvince")
                .request(new SimpleCallBack<BaseBean<List<PickerDataBean>>>() {

                    @Override
                    public void onSuccess(BaseBean<List<PickerDataBean>> data) {
                        provinceList = data.getData();
//                        provinceList = data;
                        //*/ 初始化默认选中的省、市、区
                        mCurrentProviceName = data.getData().get(0).getName();
                        cityList = data.getData().get(0).getCity();
                        if (cityList!= null && !cityList.isEmpty()) {
                            mCurrentCityName = cityList.get(0).getName();
                            reaList = cityList.get(0).getRea();
                            mCurrentDistrictName = reaList.get(0).getName();
                            townList = reaList.get(0).getTown();
                        }

                        //*/
                        mProvinceDatas = new String[data.getData().size()];
                        for (int i=0; i< provinceList.size(); i++) {
//                   // 遍历所有省的数据
                            mProvinceDatas[i] = provinceList.get(i).getName();
//                            mProvinceDatas[i] = provinceList.get(i).getName()+"/"+provinceList.get(i).getId();
                            
                            cityList = provinceList.get(i).getCity();
                            String[] cityNames = new String[cityList.size()];
                            for (int j = 0; j < cityList.size(); j++) {
                                // 遍历省下面的所有市的数据
                                cityNames[j] = cityList.get(j).getName();
//                                cityNames[j] = cityList.get(j).getName()+"/"+cityList.get(j).getId();
                                reaList = cityList.get(j).getRea();
                                String[] distrinctNameArray = new String[reaList.size()];
                                DistrictModel[] distrinctArray = new DistrictModel[reaList.size()];
                                for (int k = 0; k < reaList.size(); k++) {
                                    // 遍历市下面所有区/县的数据
                                    DistrictModel districtModel = new DistrictModel(reaList.get(k).getName(), reaList.get(k).getId() + "");
                                    // 区/县对于的邮编，保存到mZipcodeDatasMap
                                    mZipcodeDatasMap.put(reaList.get(k).getName(), reaList.get(k).getId() + "");
                                    townList = reaList.get(k).getTown();
                                    String[] townNames = new String[townList.size()];
                                    distrinctArray[k] = districtModel;
                                    distrinctNameArray[k] = districtModel.getName();
//                                    distrinctNameArray[k] = districtModel.getName()+"/"+reaList.get(k).getId();

                                    String[] townNameArray = new String[townList.size()];
                                    TownModle[] townArray = new TownModle[townList.size()];
                                    for(int s=0;s<townList.size();s++){
                                        //遍历县下面所有的镇
                                        townNames[s] = townList.get(s).getName();
                                        
                                        TownModle townModle = new TownModle(townList.get(s).getId(),townList.get(s).getName());
                                        townArray[s] = townModle;
                                        townNameArray[s] = townModle.getName();
                                    }
                                    mTownDatasMap.put(reaList.get(k).getName(),townNameArray);
                                }
                                // 市-区/县的数据，保存到mDistrictDatasMap
                                mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                            }
                            // 省-市的数据，保存到mCitisDatasMap
                            mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
                        }
                        //设置数据，有多少层级自己确定
                        pickerData.setFirstDatas(mProvinceDatas);
                        pickerData.setSecondDatas(mCitisDatasMap);
                        pickerData.setThirdDatas(mDistrictDatasMap);
                        pickerData.setFourthDatas(mTownDatasMap);
                        //初始化选择器
                        pickerView=new PickerView(SendWlActivity.this,pickerData);

                        //选择器点击回调
                        pickerView.setOnPickerClickListener(new OnPickerClickListener() {
                            //选择列表时触发的事件（手动关闭）
                            @Override
                            public void OnPickerClick(PickerData pickerData) {
                                if(startOnEnd == 1){
                                    etStart.setText(pickerData.getSelectText());
//                                    pickerData.setSe
                                }else if(startOnEnd == 2){
                                    etEnd.setText(pickerData.getSelectText());
                                }
                                
//                                int provinceId = pickerData.getPosition1();
                                journeyCityId = 0;
                                journeyAreaId = 0;
                                journeyTownId = 0;
                                
                                journeyCityId = provinceList.get(pickerData.getPosition1()).getCity().get(pickerData.getPosition2()).getId();
                                journeyAreaId = provinceList.get(pickerData.getPosition1()).getCity().get(pickerData.getPosition2()).getRea().get(pickerData.getPosition3()).getId();
                                journeyTownId = provinceList.get(pickerData.getPosition1()).getCity().get(pickerData.getPosition2()).getRea().get(pickerData.getPosition3()).getTown().get(pickerData.getPosition4()).getId();

//                                Log.d("jjjjj",cityId+" "+areaId+" "+townId);
                                pickerView.dismiss();//关闭选择器
                            }
                            //点击确定按钮触发的事件（自动关闭）
                            @Override
                            public void OnPickerConfirmClick(PickerData pickerData) {
                                if(startOnEnd == 1){
                                    etStart.setText(pickerData.getSelectText());
                                }else if(startOnEnd == 2){
                                    etEnd.setText(pickerData.getSelectText());
                                }

                                journeyCityId = 0;
                                journeyAreaId = 0;
                                journeyTownId = 0;

                                journeyCityId = provinceList.get(pickerData.getPosition1()).getCity().get(pickerData.getPosition2()).getId();
                                journeyAreaId = provinceList.get(pickerData.getPosition1()).getCity().get(pickerData.getPosition2()).getRea().get(pickerData.getPosition3()).getId();
                                journeyTownId = provinceList.get(pickerData.getPosition1()).getCity().get(pickerData.getPosition2()).getRea().get(pickerData.getPosition3()).getTown().get(pickerData.getPosition4()).getId();
                            }
                        });
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtils.showT("失败了");
                    }
                });


    }

    @OnClick({R.id.ll_classify, R.id.ll_label, R.id.bt_next,R.id.rl_end,
            R.id.common_back, R.id.tv_type, R.id.show_area_rl,R.id.rl_start})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_classify:
                break;

            case R.id.ll_label:
                break;
            case R.id.show_area_rl:
                if (0 != options1Items.size()) {
                    if (!FastUtils.isFastDoubleClick()) {
                        //判断软键盘是否打开，为true则关闭，否则不处理
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        boolean isOpen = imm.isActive();
                        if (isOpen) {
                            closrKeyboard();
                        }
                        provinceId = "1";// 省id
                        cityId = "2";//市 id
                        distristId = "3";//区id
                        //城市选择弹出框
                        CityPickerPopWindow2 mPopWindow = new CityPickerPopWindow2(this, options1Items);
                        mPopWindow.showPopupWindow(root_layout);
                        mPopWindow.setCityPickListener(this);
                    }
                }
                break;
            case R.id.ll_select_num:
                break;

            case R.id.tv_type:
                break;
            case R.id.bt_next:
//                if (TextUtils.isEmpty(etTitle.getText())) {
//                    ToastUtil.showCustomToast("请填写标题");
//                    return;
//                }
                if (TextUtils.isEmpty(etTxtra.getText())) {
                    ToastUtil.showCustomToast("请填写联系人电话!");
                    return;
                }
                if (etFormat.getText().length() == 0) {
                    ToastUtil.showCustomToast("请填写公司名称!");
                    return;
                }


                if (0 == show_area_tv.getText().length()) {
                    ToastUtil.showCustomToast("请选择公司地址!");
                    return;
                }

                String la = Prefer.getInstance().obtainLocation(this).substring(0, Prefer.getInstance().obtainLocation(this).indexOf(","));
                String lon = Prefer.getInstance().obtainLocation(this).substring(
                        Prefer.getInstance().obtainLocation(this).indexOf(",") + 1,
                        Prefer.getInstance().obtainLocation(this).length());
                
                mSubmit(la,lon);
//                String location=Prefer.obtainReLocation(SendWlActivity.this);
//                map.put("token",Prefer.getInstance().getToken());
//                map.put("title",etTitle.getText().toString().trim());
//                map.put("supply_cate_id",fabricId);
//                map.put("typeid","1");
//                map.put("price_company","");
//                map.put("spec",etFormat.getText().toString().trim());
//                map.put("nums_company","");
//                map.put("content",etTxtra.getText().toString().trim());
//                mSubmit(map);
                break;
            case R.id.common_back:
                finish();
                break;
            case R.id.rl_start:
                startOnEnd = 1;
                pickerView.show(rlStart);
                break;
            case R.id.rl_end:
                startOnEnd = 2;
                initProvinceDatas();
                pickerView.show(rlEnd);
                break;
        }
    }

    //发布物流信息
    private void releaseLogistics() {
//        
    }



    private void mSubmit(final String la, final String lon){
        HashMap<String,String> parmas=new HashMap<>();
        parmas.put("token",Prefer.getInstance().getToken());
        parmas.put("type","1");
        UploadRequest uploadRequest= SuperHttp.upload("api/filepic/filePic");
        if(images!=null){
            for (int i=0;i<images.size();i++){
                uploadRequest.addImageFile("file"+i,new File(images.get(i).path));
            }
        }
        else {
            ToastUtil.showCustomToast("请选择图片");
            return;
        }

        uploadRequest.addParams(parmas);

        showLoading();
        uploadRequest.request(new SimpleCallBack<BaseBean<List<ImgBean>>>() {
            @Override
            public void onFail(int errCode, String errMsg) {
                ToastUtil.showCustomToast(errMsg);
                hideLoading();
            }

            @Override
            public void onSuccess(BaseBean<List<ImgBean>> data) {
                ToastUtils.showT("成功");
                StringBuilder stringBuilder=new StringBuilder();
                for (int i=0;i<data.getData().size();i++){
                    stringBuilder.append(data.getData().get(i).getId()+",");
                }
                map.clear();
                
                map.put("attachment_id",stringBuilder.toString());

                map.put("token",Prefer.getInstance().getToken());
                map.put("name",etFormat.getText().toString());
                map.put("contact",etTxtra.getText().toString());
                map.put("telephone",etPhone.getText().toString());
                map.put("tel","");
                map.put("city_start",journeyCityId+"");
                map.put("area_start",journeyAreaId+"");
                map.put("route_start",journeyTownId+"");
                map.put("route_channel","");
                map.put("city_end",journeyCityId+"");
                map.put("area_end",journeyAreaId+"");
                map.put("route_end",journeyTownId+"");
                map.put("traffic","100");
                map.put("company_province",provinceId);
                map.put("company_city",cityId);
                map.put("company_area",distristId);
                map.put("company_add",detailEt.getText().toString());
                map.put("certificate_id","");
                map.put("long",lon);
                map.put("lat",la);
                
                Log.d("addInfo",Prefer.getInstance().getToken()+" "+etFormat.getText().toString()+" "+
                        etTxtra.getText().toString()+" "+etPhone.getText().toString()+" "+journeyCityId+" "+
                        journeyAreaId+" "+journeyTownId+" "+journeyCityId+" "+
                        journeyAreaId+" "+journeyTownId+" "+provinceId+" "+distristId+" "+detailEt.getText().toString()+
                stringBuilder.toString());
//                SuperHttp.post("api/myapplication/appLogisticsAdd")
//                .addParams(map)
//                .request(new SimpleCallBack<PostingModle>() {
//                    @Override
//                    public void onSuccess(PostingModle data) {
//                        ToastUtils.showT(data.getMessage());
//                        finish();
//                    }
//
//                    @Override
//                    public void onFail(int errCode, String errMsg) {
//                        ToastUtils.showT(errMsg);
//                    }
//                });
//                Intent intent=new Intent(SendExhibitionActivity.this, PubSettlementActivity.class);
//                intent.putExtra("params",map);
//                startActivity(intent);
//                finish();
//
                hideLoading();
            }
        });
    }

    /**
     * 产品数量或产品单价的弹窗
     */
    private void showJobPickciew(final String[] mCateList, final int type) {
        if (mCateList.length == 0) {
            MyToast("暂无可选项目");
            return;
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < mCateList.length; i++) {
            list.add(mCateList[i]);
        }
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置

                String companyType = mCateList[options1];
                if (type == 1) {
//                    tv_mi.setText(mCateList[options1]);
                } else {
//                    one_price_tv.setText(mCateList[options1]);
                }
            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.blue))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.black))//取消按钮文字颜色.build();
                .setCyclic(false, false, false)
                .build();
        pvOptions.setPicker(list);//一级选择器
        pvOptions.show();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoaderForPicker());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(SendWlActivity.this, ImageGridActivity.class);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                break;
            default:
                //打开预览
//                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
//                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
//                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
//                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        }
    }

    private void getLabelData() {
        ToastUtils.showT(mainId + "/");
        String token = Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyLabelMatching")
                .addParam("supply_cate_id", mainId)
                .request(new SimpleCallBack<BaseBean<ArrayList<LabelBean>>>() {
                    @Override
                    public void onSuccess(BaseBean<ArrayList<LabelBean>> data) {
                        if (data.getCode() == 0) {
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }
                        listLabel = new ArrayList<>();
                        listLabel.addAll(data.getData());

                        labelCategaryAdapter = new LabelCategaryAdapter(SendWlActivity.this, listLabel);
                        gridView.setAdapter(labelCategaryAdapter);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
    }

    //获取供求默认提示
    private void getTips() {
        String token = Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyPrompt")
                .addParam("supply_cate_id", fabricId)
                .request(new SimpleCallBack<BaseBean<ArrayList<PublishTip>>>() {
                    @Override
                    public void onSuccess(BaseBean<ArrayList<PublishTip>> data) {

                        if (data.getCode() == 0) {
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }

                        listsCateName = new ArrayList<>();
                        listsCateName.addAll(data.getData());
                        setLableName();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
    }

    //设置供求默认提示
    private void setLableName() {
        if (0 != listsCateName.size()) {
            for (int i = 0; i < listsCateName.size(); i++) {
                if ("101".equals(listsCateName.get(i).getId())) {//规格
                    mSpecs = listsCateName.get(i).getPrompt();
                }

                if ("102".equals(listsCateName.get(i).getId())) {//补充说明
                    mContents = listsCateName.get(i).getPrompt();
                }
                if ("100".equals(listsCateName.get(i).getId())) {//单价单位
                    mOnePriceUnits = listsCateName.get(i).getPrompt();
                }
                if ("99".equals(listsCateName.get(i).getId())) {//单价的提示
                    mOnePrices = listsCateName.get(i).getPrompt();
                }

                if ("98".equals(listsCateName.get(i).getId())) {//数量单位
                    mNumUnits = listsCateName.get(i).getPrompt();
                }
                if ("97".equals(listsCateName.get(i).getId())) {//数量
                    mNumberss = listsCateName.get(i).getPrompt();
                }
                if ("96".equals(listsCateName.get(i).getId())) {//标题
                    mTitles = listsCateName.get(i).getPrompt();
                }
            }

            etTitle.setHint(mTitles[0]);
            etFormat.setHint(mSpecs[0]);
//            etKoufu.setHint(mOnePrices[0]);
            etTxtra.setHint(mContents[0]);
//            tv_mi.setText(mNumUnits[0]);
//            one_price_tv.setText(mOnePriceUnits[0]);
        }
    }


    private void mSubmit(final HashMap<String, String> map) {
        showLoading();
        Intent intent = new Intent(this, PubSettlementActivity.class);
        intent.putExtra("params", map);
        intent.putExtra("type", type);
        startActivity(intent);
        hideLoading();
    }

    private void initJsonData(Context context) {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(context, "region.json");//获取assets目录下的json文件数据

        ArrayList<ProvinceBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<ProvinceBean.TwoRegBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<ProvinceBean.TwoRegBean.ThreeRegBean> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getTwo_reg().size(); c++) {//遍历该省份的所有城市
                CityList.add(jsonBean.get(i).getTwo_reg().get(c));//添加城市
                List<ProvinceBean.TwoRegBean.ThreeRegBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (null == jsonBean.get(i).getTwo_reg().get(c).getThree_reg()
                        || jsonBean.get(i).getTwo_reg().get(c).getThree_reg().size() == 0) {
                    City_AreaList.add(new ProvinceBean.TwoRegBean.ThreeRegBean());
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getTwo_reg().get(c).getThree_reg());
                }
                Province_AreaList.addAll(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.addAll(CityList);

            /**
             * 添加地区数据
             */
            options3Items.addAll(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData(SendWlActivity.this);
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    public ArrayList<ProvinceBean> parseData(String result) {//Gson 解析
        ArrayList<ProvinceBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                ProvinceBean entity = gson.fromJson(data.optJSONObject(i).toString(), ProvinceBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    @Override
    public void pickValue(String value) {
        province = value.split("-")[0];
        city = value.split("-")[1];
        if (value.split("-").length >= 3) {
            district = value.split("-")[2];
            show_area_tv.setText(province + "-" + city + "-" + district);
        } else {
            district = " ";
            show_area_tv.setText(province + "-" + city);
        }

        for (int i = 0; i < options1Items.size(); i++) {
            if (province.equals(options1Items.get(i).getName())) {
                provinceId = options1Items.get(i).getId() + "";
            }
        }

        for (int i = 0; i < options2Items.size(); i++) {
            if ((options2Items.get(i).getName().contains(city))) {
                cityId = options2Items.get(i).getId() + "";
            }
        }

        if (null != options3Items && 0 != options3Items.size()) {
            for (int i = 0; i < options3Items.size(); i++) {

                if (!TextUtils.isEmpty(district) && options3Items.get(i).getName().contains(district)) {
                    distristId = options3Items.get(i).getId() + "";
                }
            }
        } else {
            distristId = " ";
        }

        Log.e("TAGPROVINCE_ID", provinceId + ":" + cityId + ":" + distristId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
